package com.alisls.demo.sso.crm.filter;

import com.alisls.demo.sso.crm.util.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录检查过滤器
 *
 * @author Ke Wang
 */
@Component
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Value("${client.domain-url}")
    private String clientDomainUrl;

    @Value("${client.logout-url}")
    private String clientLogoutUrl;

    @Value("${sso.login-check-url}")
    private String loginCheckUrl;

    @Value("${sso.token-check-url}")
    private String tokenCheckUrl;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("执行登录检查过滤器");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 请求地址
        String requestPath = request.getRequestURI();

        // 1. 判断本地是否登录（Session中isLogin为true）
        HttpSession session = request.getSession();
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        if (isLogin != null && isLogin) {
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("本地Session状态为已登录，跳出过滤器");
            return;
        }

        // 2. 判断是否带有token
        String token = request.getParameter("token");
        System.out.println("本地Session状态为未登录，检查请求参数是否带有Token");
        if (token != null && token.length() > 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("token", token);
            params.put("clientLogoutUrl", clientLogoutUrl);
            params.put("sessionId", session.getId());
            String result = HttpUtil.sendPost(tokenCheckUrl, params);
            System.out.println("请求参数带有Token，对Token有效性进行校验");
            if ("true".equalsIgnoreCase(result)) {
                request.getSession().setAttribute("isLogin", true);
                filterChain.doFilter(request, response);
                System.out.println("Token校验通过，设置本地Session状态为已登录");
                return;
            }
        }

        System.out.println("本地Session状态为未登录，请求参数中不带有Token，重定向到SSO登录检查URL");
        response.sendRedirect(loginCheckUrl + "?redirect=" + clientDomainUrl + requestPath + "&clientLogoutUrl=" + clientLogoutUrl);
    }

}
